package com.example.schedulemanager.view;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CalendarView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.schedulemanager.R;
import com.example.schedulemanager.model.Schedule;
import com.example.schedulemanager.utils.AlarmScheduler;
import com.example.schedulemanager.view.adapter.ScheduleAdapter;
import com.example.schedulemanager.viewmodel.ScheduleViewModel;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    
    private static final int NOTIFICATION_PERMISSION_REQUEST_CODE = 1001;
    private ScheduleViewModel scheduleViewModel;
    private ScheduleAdapter adapter;
    private String selectedDate;
    private CalendarView calendarView;
    private RecyclerView recyclerView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 初始化视图
        calendarView = findViewById(R.id.calendarView);
        recyclerView = findViewById(R.id.recyclerView);
        FloatingActionButton fab = findViewById(R.id.fab);
        
        // 设置RecyclerView支持滑动
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        
        adapter = new ScheduleAdapter();
        recyclerView.setAdapter(adapter);
        
        // 初始化ViewModel
        scheduleViewModel = new ViewModelProvider(this).get(ScheduleViewModel.class);
        
        // 设置当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        selectedDate = sdf.format(new Date());
        
        // 设置日历视图
        calendarView.setOnDateChangeListener((view, year, month, dayOfMonth) -> {
            selectedDate = String.format(Locale.getDefault(), "%04d-%02d-%02d", year, month + 1, dayOfMonth);
            loadSchedulesForDate(selectedDate);
        });
        
        // 设置FAB点击事件
        fab.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, AddScheduleActivity.class);
            intent.putExtra("selected_date", selectedDate);
            startActivity(intent);
        });
        
        // 设置适配器点击事件
        adapter.setOnItemClickListener(new ScheduleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Schedule schedule) {
                Intent intent = new Intent(MainActivity.this, EditScheduleActivity.class);
                intent.putExtra("schedule_id", schedule.getId());
                startActivity(intent);
            }
            
            @Override
            public void onDeleteClick(Schedule schedule) {
                showDeleteDialog(schedule);
            }
            
            @Override
            public void onCompletionToggle(Schedule schedule) {
                toggleScheduleCompletion(schedule);
            }
        });
        
        // 加载当前日期的日程
        loadSchedulesForDate(selectedDate);
        
        // 启动时显示当前日期的所有日程
        showTodaySchedulesDialog();

        // 请求笔记软件提示权限
        requestNotificationPermission();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        loadSchedulesForDate(selectedDate);
    }
    
    private void loadSchedulesForDate(String date) {
        scheduleViewModel.getSchedulesByDate(date).observe(this, schedules -> {
            adapter.setSchedules(schedules);
            if (schedules.isEmpty()) {
                recyclerView.setVisibility(View.GONE);
                findViewById(R.id.emptyView).setVisibility(View.VISIBLE);
            } else {
                recyclerView.setVisibility(View.VISIBLE);
                findViewById(R.id.emptyView).setVisibility(View.GONE);
            }
        });
    }
    
    private void toggleScheduleCompletion(Schedule schedule) {
        boolean newStatus = !schedule.isCompleted();
        schedule.setCompleted(newStatus);
        
        // 更新数据库中的完成状态
        scheduleViewModel.updateCompletionStatus(schedule.getId(), newStatus);
        
        // 显示提示信息
        String message = newStatus ? getString(R.string.schedule_completed) : getString(R.string.schedule_uncompleted);
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        
        // 重新加载日程列表以更新排序
        loadSchedulesForDate(selectedDate);
    }
    
    private void showTodaySchedulesDialog() {
        scheduleViewModel.getSchedulesByDate(selectedDate).observe(this, schedules -> {
            if (!schedules.isEmpty()) {
                StringBuilder message = new StringBuilder("今日日程：\n\n");
                for (Schedule schedule : schedules) {
                    String status = schedule.isCompleted() ? "✓" : "○";
                    message.append(status).append(" ").append(schedule.getTitle())
                           .append(" (").append(schedule.getTime()).append(")\n");
                }
                
                new AlertDialog.Builder(this)
                        .setTitle("今日日程提醒")
                        .setMessage(message.toString())
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }
    
    private void showDeleteDialog(Schedule schedule) {
        new AlertDialog.Builder(this)
                .setTitle("删除日程")
                .setMessage("确定要删除这个日程吗?")
                .setPositiveButton("删除", (dialog, which) -> {
                    // 取消闹钟
                    AlarmScheduler.cancelAlarm(getApplicationContext(), schedule);
                    // 从数据库删除
                    scheduleViewModel.delete(schedule);
                    Toast.makeText(this, R.string.deleted, Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) !=
                    android.content.pm.PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
                        NOTIFICATION_PERMISSION_REQUEST_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == NOTIFICATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, R.string.allowed, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, R.string.notification, Toast.LENGTH_LONG).show();
            }
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_today) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            selectedDate = sdf.format(new Date());
            calendarView.setDate(System.currentTimeMillis());
            loadSchedulesForDate(selectedDate);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 